import dayjs from 'dayjs'
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import { info, error } from '@/library/tool-kits/log'
import { languagesSupported } from './language'

export class I18nConstants {
  /** 默认语言 */
  static readonly defaultLocale = 'zh-CN'

  /** 支持语言 */
  static readonly locales = languagesSupported
}

const loadLangResources = async (lang: string) => {
  const common = (await import(`./${lang}/common`)).default

  return {
    translation: {
      common,
    },
  }
}

const resources: Record<string, any> = {}

I18nConstants.locales.forEach(async (locale) => {
  resources[locale] = await loadLangResources(locale)
})

i18n.use(initReactI18next)
  .init({
    lng: undefined,
    fallbackLng: I18nConstants.defaultLocale,
    interpolation: {
      // 取消转义，react本身有该功能
      escapeValue: false,
    },
    // 启用自动保存缺失的翻译键
    saveMissing: true,
    // 如果没有显式指定 defaultNS，i18next 会将第一个定义的命名空间作为默认命名空间
    resources,
  }).then(() => {
    info('i18n', `- Current language: [${i18n.language}]`)
  })

i18n.on('languageChanged', (language) => {
  info(
    'i18n',
    `i18n language has changed [${language}]`,
  )
  document.title = i18n.t('common.document.title')
})

i18n.on('missingKey', (lngs, namespace, key) => {
  error(
    'i18n',
    `emptyKey: ${key} >> [locale: ${lngs.toString()}; ns: ${namespace}]`,
  )
})

i18n
  .services
  .formatter!
  .add('DD/MM/YY', (value) => dayjs(value).format('DD/MM/YYYY'))

i18n
  .services
  .formatter!
  .add('YYYY-MM-DD', (value) => dayjs(value).format('YYYY-MM-DD'))

export default i18n
